package com.key.puzzlemodel.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.graphics.drawable.toBitmap
import com.key.puzzlemodel.R
import com.key.puzzlemodel.util.BitmapUtil


/**
 *
 * @功能描述:     自定义缩放，移动，宫格显示的ImageView
 * @创建时间:     2022/1/18
 * @创建者:       阳
 * @修改时间:     2022/1/18
 * @修改者:       阳
 */
class CutterManImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    AppCompatImageView(context, attrs) {

    private var lineColor = 0 // 裁剪框相关线条颜色
    private var borderWidth = 0 // 裁剪边框线条宽度


    //监听图片缩放
    private var mScaleDetector: ScaleGestureDetector? = null

    //监听图片移动
    private var mGestureDetector: GestureDetector? = null

    //当前的缩放比例
    private var mScaleFactor = 1.0f

    //绘制图片的起始位置
    private var mPosX = 0f
    private var mPosY = 0f

    //绘制的图片总的宽高
//    private var postHeight = 0f
//    private var postWidth = 0f


    //单元格的宽度和高度
    var itemWidth: Float = 0f
    var itemHeight: Float = 0f

    //横向图片个数
    var horizontalPicNumber: Int = 3

    //纵向图片个数
    var verticalPicNumber: Int = 3

    init {
        context.theme.obtainStyledAttributes(attrs, R.styleable.CutterManStyle, 0, 0).apply {
            try {
                lineColor =
                    getInteger(R.styleable.CutterManStyle_cutterManLineColor, R.color.color0A0A0A)

                borderWidth = getInteger(
                    R.styleable.CutterManStyle_cutterManBorderWidth,
                    BitmapUtil.dip2px(context, 3f)
                )

                horizontalPicNumber = getInteger(R.styleable.CutterManStyle_horizontalPicNumber, 3)
                verticalPicNumber = getInteger(R.styleable.CutterManStyle_verticalPicNumber, 3)
            } finally {
                //资源回收
                recycle()
            }
        }

        mScaleDetector = ScaleGestureDetector(context, SimpleScaleListenerImpl())
        mGestureDetector = GestureDetector(context, SimpleGestureListenerImpl())
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (measuredHeight != 0 && measuredWidth != 0) {
            var viewWidth = 0
            var viewHeight = 0

            //九宫格 和四宫格
            if ((horizontalPicNumber * 1.0f / verticalPicNumber * 1.0f) == 1.0f) {
                viewWidth = measuredWidth
                viewHeight = measuredWidth
            } else if (horizontalPicNumber / verticalPicNumber == 3) {
                //3宫格
                viewWidth = measuredWidth
                viewHeight = measuredWidth / 3
            } else {
                //6宫格
                viewWidth = measuredWidth
                viewHeight = measuredWidth * 2 / 3
            }

            //计算当前单元格的宽度和高度
            this.itemWidth = (viewWidth / horizontalPicNumber).toFloat()
            this.itemHeight = (viewHeight / verticalPicNumber).toFloat()

            setMeasuredDimension(viewWidth, viewHeight + 1)
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec + 1)
        }

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //https://blog.csdn.net/weixin_42247720/article/details/103499425
        //深色画笔
        var linePaint = Paint()
        linePaint.color = resources.getColor(lineColor)

        //设置线条的宽度
        linePaint.strokeWidth = borderWidth.toFloat()

        //画出宫格的竖线
        //从 1开始 就不会画靠边的边界线
        for (index in 1 until horizontalPicNumber) {
            canvas.drawLine(
                index * itemWidth,
                0f,
                index * itemWidth,
                height.toFloat(),
                linePaint
            )
        }
        //画出宫格的横线
        for (index in 1 until verticalPicNumber) {
            canvas.drawLine(
                0f,
                index * itemHeight,
                width.toFloat(),
                index * itemHeight,
                linePaint
            )
        }
    }


    //宫格数量
    fun setSquaresNumber(horNumber: Int, verNumber: Int) {
        horizontalPicNumber = horNumber
        verticalPicNumber = verNumber
        //当前的缩放比例
        mScaleFactor = 1.0f
        requestLayout()
    }


    /**
     * @direction 0:纵向 ， 1 ：横向
     */
    fun setImageMatrixLayout(direction: Int) {

        scaleType = ScaleType.MATRIX

        var viewWidth = measuredWidth
        var viewHeight = measuredHeight
        var mBitmap = drawable.toBitmap()
        if (viewWidth <= 0 || viewHeight <= 0 || null == mBitmap) {
            return
        }

        var ratio = if (0 == direction) {
            viewHeight * 1.0f / mBitmap.height
        } else {
            1.0f * viewWidth / mBitmap.width
        }
        //进行缩放限制
        if (ratio >= 4.0f) {
            ratio = 4.0f
        }
        if (ratio <= 0.3f) {
            ratio = 0.3f
        }
        var dx = (viewWidth - mBitmap.width) * 1.0f / 2
        var dy = (viewHeight - mBitmap.height) * 1.0f / 2

        var imageMatrix = Matrix()
        //设置缩放
        imageMatrix.setScale(
            ratio, ratio, (mBitmap.width / 2).toFloat(), (mBitmap.height / 2).toFloat()
        )
        //图片移动
        imageMatrix.postTranslate(dx, dy)

        setImageMatrix(imageMatrix)

        //存储信息
        setImageLocation(ratio, dx, dy)
        invalidate()
    }


    /**
     * 设置view 的缩放系数，坐标点
     * 并 重置移动的宽高度
     */
    fun setImageLocation(ratio: Float, dx: Float, dy: Float) {
        //当前的缩放比例
        mScaleFactor = ratio
        //绘制图片的起始位置
        mPosX = dx
        mPosY = dy
        //绘制的图片总的宽高
//        postHeight = 0f
//        postWidth = 0f
    }


    override fun onTouchEvent(event: MotionEvent): Boolean {
//        return super.onTouchEvent(event)

        //双指缩放
        mScaleDetector!!.onTouchEvent(event)
        //单指移动
        mGestureDetector!!.onTouchEvent(event)

//        val action = MotionEventCompat.getActionMasked(event)
//        when (action) {
//            MotionEvent.ACTION_DOWN -> {
//                val pointerIndex = MotionEventCompat.getActionIndex(event)
//                mActivePointerId = MotionEventCompat.getPointerId(event, pointerIndex)
//                lastX = event.x
//                lastY = event.y
//            }
//            MotionEvent.ACTION_MOVE -> {
//
//                // 找到活动指针的索引并获取它的位置
//                val pointerIndex = MotionEventCompat.findPointerIndex(event, mActivePointerId)
//                val currentX = MotionEventCompat.getX(event, pointerIndex)
//                val currentY = MotionEventCompat.getY(event, pointerIndex)
//                mPosX += currentX - lastX
//                mPosY += currentY - lastY
//                Log.e("手指活动：", "${currentX - lastX} -- ${currentY - lastY}，mPosX = $mPosX ,$mPosY ")
//                imageMatrix.setTranslate(mPosX, mPosY)
//                invalidate()
//                lastX = currentX
//                lastY = currentY
//            }
//            MotionEvent.ACTION_POINTER_UP -> {
//                val pointerIndex = MotionEventCompat.getActionIndex(event)
//                val pointerId = MotionEventCompat.getPointerId(event, pointerIndex)
//                if (pointerId == mActivePointerId) {
//                    // This was our active pointer going up. Choose a new
//                    // active pointer and adjust accordingly.
//                    val newPointerIndex = if (pointerIndex == 0) 1 else 0
//                    lastX = MotionEventCompat.getX(event, newPointerIndex)
//                    lastY = MotionEventCompat.getY(event, newPointerIndex)
//                    mActivePointerId = MotionEventCompat.getPointerId(event, newPointerIndex)
//                }
//            }
//            MotionEvent.ACTION_UP -> {
//                mActivePointerId = INVALID_POINTER_ID
//            }
//        }

        return true
    }


    //缩放
    private inner class SimpleScaleListenerImpl :
        ScaleGestureDetector.SimpleOnScaleGestureListener() {
        override fun onScale(detector: ScaleGestureDetector): Boolean {


            var simpleScale = detector.scaleFactor

            if (mScaleFactor * simpleScale >= 4.0f || mScaleFactor * simpleScale <= 0.3f) {
                simpleScale = 1.0f
            } else {
                mScaleFactor *= simpleScale
            }
            //Log.e("缩放：", "mScaleFactor == $mScaleFactor  ")

//            mScaleFactor *= simpleScale
            //缩放倍数范围：0.3～4
//            mScaleFactor = max(0.3f, min(mScaleFactor, 4.0f))

            //以图片的中心为基点进行缩放
            imageMatrix.postScale(
                simpleScale, simpleScale,
                mPosX + measuredWidth / 2,
                mPosY + measuredHeight / 2
            )
            invalidate()
            return true
        }
    }

    //移动
    private inner class SimpleGestureListenerImpl : GestureDetector.SimpleOnGestureListener() {
        override fun onScroll(
            e1: MotionEvent,
            e2: MotionEvent,
            distanceX: Float,
            distanceY: Float
        ): Boolean {
            //************* 不能再这里处理临界问题，因为 宽高度会随时变化，处理起来有问题， 必须在ondraw里面处理临界问题 **************

            mPosX = -distanceX
            mPosY = -distanceY

            //记录总的长度
//            postWidth += mPosX
//            postHeight += mPosY
            //Log.e("移动：", "$mPosX --$mPosY  ")
            imageMatrix.postTranslate(mPosX, mPosY)
            invalidate()
            return true


//            Log.e("移动：", "distanceX == $distanceX mPosY == $distanceY  ")
//            Log.e("移动：", "left == $left right == $right  top=$top  bottom = $bottom ")
//            mPosX = -distanceX
//            mPosY = -distanceY
            //左侧的判断  postWidth + distanceX >= 525  正数
            //右侧的判断   postWidth =                  负数
            //底部的判断  负数
            //顶部的判断  正数

            //abs(postHeight) + abs(distanceY) >= (measuredHeight / 2) ||
            //                abs(postWidth) + abs(distanceX) >= (measuredWidth / 2)

//            Log.e(
//                "移动：",
//                "postWidth == $postWidth  distanceX == $distanceX}"
//            )
//
//            //左侧
//            if (distanceX > 0) {
//                if ((postWidth + distanceX) / mScaleFactor > (measuredWidth / 4 * 3)) {
//                    mPosX = 0f
//                } else {
//                    mPosX = distanceX
//                }
//                Log.e("左侧移动：", "--$mPosX")
//            } else {
//                if ((postWidth + distanceX) / mScaleFactor < -(measuredWidth / 4 * 3)) {
//                    mPosX = 0f
//                } else {
//                    mPosX = distanceX
//                }
//                Log.e("右侧移动：", "--$mPosX")
//            }


//            if (postWidth + distanceX < -(measuredWidth / 2)
//                || postWidth - distanceX > (measuredWidth / 2)
////                || postHeight - distanceY <= -(measuredHeight / 2)
////                || postHeight - distanceY >= (measuredHeight / 2)
//            ) {
//                mPosX = 0f
//                mPosY = 0f
//            } else {
//                mPosX = distanceX
//                mPosY = distanceY
//            }

//            if (abs(postHeight) - abs(distanceY) >= (measuredHeight / 2)) {
//                mPosX = 0f
//                mPosY = 0f
//            } else {
//            mPosX = -distanceX
//            mPosY = -distanceY
//            }


        }

    }

}























